package com.jerry.secondkill.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.spring4.context.SpringWebContext;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;

import com.jerry.secondkill.domain.User;
import com.jerry.secondkill.redis.RedisService;
import com.jerry.secondkill.redis.key.GoodsKey;
import com.jerry.secondkill.result.Result;
import com.jerry.secondkill.service.GoodsService;
import com.jerry.secondkill.service.UserService;
import com.jerry.secondkill.vo.GoodsDetailVo;
import com.jerry.secondkill.vo.GoodsVo;

@Controller
@RequestMapping("/goods")
public class GoodsController {

	private static Logger log = LoggerFactory.getLogger(UserController.class);
	
	@Autowired
	UserService userService;
	@Autowired
	RedisService redisService;
	@Autowired
	GoodsService goodsService;
	@Autowired
	ThymeleafViewResolver thymeleafViewResolver;
	@Autowired
	ApplicationContext applicationContext;
	
	
	// *****************************  页面静态化 开始 ************************************* //
    /**
     * 页面使用html+ajax,后端返回json数据，这就是所谓的前后端分离，页面静态化
     * @param model
     * @param user
     * @param goodsId
     * @return
     */
	@RequestMapping("/detailStatic/{goodsId}")
    @ResponseBody
    public Result<GoodsDetailVo> detailStatic(Model model, User user, @PathVariable("goodsId")long goodsId) {
    	//通过商品id获取秒杀商品
    	GoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId);

    	long startAt = goods.getStartDate().getTime();
    	long endAt = goods.getEndDate().getTime();
    	long now = System.currentTimeMillis();
    	int seckillStatus = 0;
    	int remainSeconds = 0;
    	if(now < startAt ) {//秒杀还没开始，倒计时
    		seckillStatus = 0;
    		remainSeconds = (int)((startAt - now )/1000);
    	}else if(now > endAt){//秒杀已经结束
    		seckillStatus = 2;
    		remainSeconds = -1;
    	}else {//秒杀进行中
    		seckillStatus = 1;
    		remainSeconds = 0;
    	}
    	GoodsDetailVo vo = new GoodsDetailVo();
    	vo.setGoods(goods);
    	vo.setUser(user);
    	vo.setRemainSeconds(remainSeconds);
    	vo.setSeckillStatus(seckillStatus);
    	return Result.success(vo);
    }
    // *****************************  页面静态化 结束 ************************************* //
    
    
	// *****************************  使用缓存 开始 ************************************* //
	/**
	 * 此处使用页面级缓存
	 * 页面级缓存：整个页面做为缓存
	 * @param request
	 * @param response
	 * @param model
	 * @param user
	 * @return
	 */
    @RequestMapping(value="/toListCache", produces="text/html")
    @ResponseBody
    public String listCache(HttpServletRequest request, 
    				   HttpServletResponse response,
    				   Model model,
    				   User user) {
    	model.addAttribute("user", user);
    	
    	//取缓存
    	String html = redisService.get(GoodsKey.getGoodsList, "", String.class);
    	if(!StringUtils.isEmpty(html)) {
    		return html;
    	}
    	
    	//查询商品列表
    	List<GoodsVo> goodsList = goodsService.listGoodsVo();
    	log.info("goods list cache=="+goodsList.toString());
    	model.addAttribute("goodsList", goodsList);
    	
    	SpringWebContext ctx = new SpringWebContext(
    			request,
    			response,
    			request.getServletContext(),
    			request.getLocale(), 
    			model.asMap(), 
    			applicationContext);
    	//手动渲染
    	html = thymeleafViewResolver.getTemplateEngine().process("goods_list", ctx);
    	if(!StringUtils.isEmpty(html)) {
    		redisService.set(GoodsKey.getGoodsList, "", html);
    	}
    	return html;
    }
    
    /**
     * 此处使用URL缓存，（ps:个人感觉URL缓存和页面缓存没啥区别）
     * @param request
     * @param response
     * @param model
     * @param user
     * @param goodsId
     * @return
     */
    @RequestMapping(value="/toDetailCache/{goodsId}", produces="text/html")
    @ResponseBody
    public String detailCache(
    		HttpServletRequest request, 
    		HttpServletResponse response,
    		Model model, 
    		User user, 
    		@PathVariable("goodsId")long goodsId) {
    	model.addAttribute("user", user);
    	
    	//取缓存
    	String html = redisService.get(GoodsKey.getGoodsDetail, ""+goodsId, String.class);
    	if(!StringUtils.isEmpty(html)) {
    		return html;
    	}
    	
    	//通过商品id获取秒杀商品
    	GoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId);
    	log.info("goods detail cache=="+goods.toString());
    	model.addAttribute("goods", goods);
    	
    	long startAt = goods.getStartDate().getTime();
    	long endAt = goods.getEndDate().getTime();
    	long now = System.currentTimeMillis();
    	
    	int seckillStatus = 0;
    	int remainSeconds = 0;
    	if(now < startAt ) {//秒杀还没开始，倒计时
    		seckillStatus = 0;
    		remainSeconds = (int)((startAt - now )/1000);
    	}else if(now > endAt){//秒杀已经结束
    		seckillStatus = 2;
    		remainSeconds = -1;
    	}else {//秒杀进行中
    		seckillStatus = 1;
    		remainSeconds = 0;
    	}
    	model.addAttribute("seckillStatus", seckillStatus);
    	model.addAttribute("remainSeconds", remainSeconds);
        
    	//手动渲染
    	SpringWebContext ctx = new SpringWebContext(
    			request,
    			response,
    			request.getServletContext(),
    			request.getLocale(), 
    			model.asMap(), 
    			applicationContext );
    	html = thymeleafViewResolver.getTemplateEngine().process("goods_detail", ctx);
    	if(!StringUtils.isEmpty(html)) {
    		redisService.set(GoodsKey.getGoodsDetail, ""+goodsId, html);
    	}
    	return html;
    }
    // *****************************  使用缓存 结束 ************************************* //
    
    // *****************************  未使用缓存 开始 ************************************* //
    @RequestMapping(value="/toList")
    public String list(Model model,User user) {
    	model.addAttribute("user", user);
    	//查询商品列表
    	List<GoodsVo> goodsList = goodsService.listGoodsVo();
    	log.info("goods list=="+goodsList.toString());
    	model.addAttribute("goodsList", goodsList);
    	return "goods_list";
    }
    
    @RequestMapping("/toDetail/{goodsId}")
    public String detail(Model model, User user, @PathVariable("goodsId")long goodsId) {
    	model.addAttribute("user", user);
    	//通过商品id获取秒杀商品
    	GoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId);
    	model.addAttribute("goods", goods);
    	
    	long startAt = goods.getStartDate().getTime();
    	long endAt = goods.getEndDate().getTime();
    	long now = System.currentTimeMillis();
    	
    	int seckillStatus = 0;
    	int remainSeconds = 0;
    	if(now < startAt ) {//秒杀还没开始，倒计时
    		seckillStatus = 0;
    		remainSeconds = (int)((startAt - now )/1000);
    	}else if(now > endAt){//秒杀已经结束
    		seckillStatus = 2;
    		remainSeconds = -1;
    	}else {//秒杀进行中
    		seckillStatus = 1;
    		remainSeconds = 0;
    	}
    	model.addAttribute("seckillStatus", seckillStatus);
    	model.addAttribute("remainSeconds", remainSeconds);
        return "goods_detail";
    }
    // *****************************  未使用缓存 结束 ************************************* //
}
